package com.lixia.lxframework.framework.system;

import com.lixia.lxframework.framework.system.ex.BusinessException;
import com.lixia.lxframework.framework.web.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import static com.lixia.lxframework.framework.system.constant.MsgConstants.*;

/**
 * 统一处理异常
 *
 * @author Administrator
 * @date 2020/6/9
 */
@Slf4j
@ControllerAdvice
public class ControllerAdviceHandler {
    /**
     * 异常处理
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(value = Throwable.class)
    @ResponseBody
    public R exceptionHandler(Exception ex) {
        log.error(ex.getMessage(), ex);
        // 处理业务异常
        if (ex instanceof BusinessException) {
            // 返回业务异常code和message;
            return R.failed(((BusinessException) ex).getCode(), ex.getMessage());
        } else if (ex instanceof DuplicateKeyException) {
            return R.failed(FAILED_CODE, EX_DUPLICATE_KEY_MSG);
        } else if (ex instanceof HttpRequestMethodNotSupportedException) {
            return R.failed(EX_METHOD_NOTSUPPORTED_CODE, EX_METHOD_NOTSUPPORTED_MSG);
        } else if (ex instanceof HttpMediaTypeNotSupportedException) {
            return R.failed(EX_HTTP_MEDIATYPE_NOTSUPPORTED_CODE, EX_HTTP_MEDIATYPE_NOTSUPPORTED_MSG);
        } else {
            return R.failed(FAILED_CODE, EX_SYSTEM_MSG.concat("异常原因：" + ex.getMessage()));
        }
    }
}
